package other;

/**
 * Created by lyyn on 2022/7/24.
 */
/*
给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，
且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1：
输入：n = 3
输出：[[1,2,3],[8,9,4],[7,6,5]]
 */
public class GenerateMatrix_59 {
    public static void main(String[] args) {
        Solution_4 solution_4 = new Solution_4();
        int n = 25;
        int[][] result = solution_4.generateMatrix(n);
        for(int i = 0;i < n;i++){
            for (int j = 0; j < n; j++) {
                System.out.print(result[i][j]+"    ");
            }
            System.out.println();
        }
    }
}
class Solution_4 {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int start_xy = 0;
        int end_xy = 1;
        int count = 1;
        int xhn = n / 2;
        int i = 0,j = 0;
        while (xhn > 0){
            i = start_xy;
            j = start_xy;
            for (;i < n - end_xy;i++) {
                result[j][i] = count;
                count++;
            }
            for (;j < n - end_xy;j++){
                result[j][i] = count;
                count++;
            }
            for ( ;j > -1 + end_xy; j--) {
                result[i][j] = count;
                count++;
            }
            for ( ;i > -1 + end_xy; i--) {
                result[i][j] = count;
                count++;
            }
            start_xy++;
            end_xy++;
            xhn--;
        }

        if (n % 2 != 0){
            result[start_xy][start_xy] = count;
        }
        return result;
    }
}